#! /bin/bash -E

# CVE-2023-38408: Remote Code Execution in OpenSSH's forwarded ssh-agent
# ./step1.sh /var/lib/apt/lists/us.archive.ubuntu.com_ubuntu_dists_jammy_main_binary-amd64_Packages
# ./step1.sh /var/lib/apt/lists/us.archive.ubuntu.com_ubuntu_dists_jammy_universe_binary-amd64_Packages
# Copyright (C) 2023 Qualys, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

trap 'echo "$LINENO"; exit 1' ERR || exit "$LINENO"
[ "$#" -ge 1 ]

dir="$(mktemp -d /tmp/step1.XXXXXXXXXX)"
cd "$dir"
exec 2>stderr
cat "$@" > Packages

while read name value; do
    [ "$name" = 'Package:' ] || continue
    echo "$value"
    filename=''
    sha256=''
    while [ -z "$filename" -o -z "$sha256" ]; do
        read name value
        [ "$name" != 'Package:' ]
        [ "$name" = 'Filename:' ] && filename="$value"
        [ "$name" = 'SHA256:' ] && sha256="$value"
    done
    wget -nv "http://archive.ubuntu.com/ubuntu/$filename" < /dev/null || continue
    filename="${filename##*/}"
    echo "$filename" >&2
    [ "$(sha256sum < "$filename")" = "$sha256  -" ] || continue
    dpkg-deb --fsys-tarfile "$filename" | (cd /; tar --keep-newer-files --wildcards -xvf - './usr/lib*' './usr/local/lib*' || true) >&2
    rm "$filename"
done < Packages

rm Packages
echo done.

